#!/usr/bin/env python
# -*- coding: utf-8 -*-

import pymysql#MySQLdb
import sys

class SQlserver():
	def __init__(self, host, user, passwd, access_mode):
		"""Constructor for SQL server"""
		self.host = host
		self.user = user
		self.passwd = passwd
		self.access_mode = access_mode
		self.error=""
		self.db_name="asfx"
		
	#def test_connection(self):
	#	"""test the connection to the SQL serveur"""
	#	try:
	#		pymysql.connect(self.host,self.user,self.passwd,db=self.db_name)
	#		self.error = ""
	#		return True
	#	except pymysql.Error, e:
	#		self.error = "Error MySQL %d: %s" % (e.args[0], e.args[1])
	#		return False

class McfConnector():
	def __init__(self, ontology, sqlserver):
		self.sqlserver = sqlserver
		self.access_mode = sqlserver.access_mode
		if ontology == 'Human anatomy (2010)':
			self.db_name = "old_mcf"
		if ontology == 'Human diseases':
			self.db_name = "asfx"
		if ontology == 'Human anatomy (2011)':
			self.db_name = "mcf" 
		try:
			self.db = pymysql.connect(sqlserver.host,sqlserver.user,sqlserver.passwd,self.db_name)
		except pymysql.Error, e:
			print "Error MySQL %d: %s" % (e.args[0], e.args[1])
			sys.exit (1)
		

	def __del__( self):
		self.db.close()

	def mcfQuery(self,query):             
		cursor = self.db.cursor ()
		#cursor = db.cursor(pymysql.cursors.DictCursor) #To get dic from database
		#    print "-> MySQL :" + qusery
		try:
			cursor.execute (query)    
			l=[]
			for data in cursor.fetchall():
				l.append(data)
		except pymysql.Error, e:
			print "Error %d: %s" % (e.args[0], e.args[1])
		cursor.close()
		return l

	def mcfQueryExec(self,query):             
		cursor = self.db.cursor ()
		try:
			res = cursor.execute (query)    
		except pymysql.Error, e:
			print "Error %d: %s" % (e.args[0], e.args[1])
			return "Error %d: %s" % (e.args[0], e.args[1])
		self.db.commit()
		cursor.close()
		return res
